<?php

function editor_name_heading(){
	global $shared_user, $app_strings, $current_language;

        $current_module_strings = return_module_language($current_language, 'edanz_Schedule');

	echo '<h5 class="calSharedUser" style="display:inline;font-size:15px"><a href = "index.php?module=edanz_Editor&action=DetailView&record='.$shared_user->id.'">'.$shared_user->full_name.'</a>';

	



	if($shared_user->isNewEditor()){
		echo '<span style="font-style:italic">&nbsp;('.$current_module_strings['LBL_NEW_EDITOR'].')</span>';
	}

	
}

function get_schedule_notes_and_probation_notes(){
	global $shared_user, $app_strings, $current_language;
	$ongoing_note_icon = SugarThemeRegistry::current()->getImageURL('ongoing_note.gif');
	$probation_icon = SugarThemeRegistry::current()->getImageURL('probation.gif');
	require_once('modules/edanz_Editor/metadata/additionalDetails.php');
	$additional_details = scheduleDetails($shared_user->id);
	$additional_details['schedule_notes'] = str_replace(array("&#039", "'"), '\&#039', $additional_details['schedule_notes']);
	if(!empty($additional_details['schedule_notes'])){
		$extra = "onmouseover=\"return overlib('" .
				str_replace(array("\rn", "\r", "\n"), array('','','<br />'), $additional_details['schedule_notes'])
				. "', CAPTION, '{$app_strings['LBL_SCHEDULE_NOTES']}"
		. "', DELAY, 200, STICKY, MOUSEOFF, 1000, WIDTH, 310, CLOSETEXT, '<img border=0  style=\'margin-left:2px; margin-right: 2px;\' src=".SugarThemeRegistry::current()->getImageURL('close.gif').">', "
				. "CLOSETITLE, '{$app_strings['LBL_ADDITIONAL_DETAILS_CLOSE_TITLE']}', CLOSECLICK, FGCLASS, 'olFgClass', "
				. "CGCLASS, 'olCgClass', BGCLASS, 'olBgClass', TEXTFONTCLASS, 'olFontClass', CAPTIONFONTCLASS, 'olCapFontClass', CLOSEFONTCLASS, 'olCloseFontClass');\" "
				. "onmouseout=\"return nd(1000);\" ";
	
				echo "<span $extra>&nbsp;<img vertical-align='middle' class='info' border='0' src='$ongoing_note_icon'></span>";
	}
	/*
				echo "<span id='adspan_" . $editor->id . "' onmouseout=\"return SUGAR.util.clearAdditionalDetailsCall()\" "
				. "onmouseover=\"lvg_dtails('$editor->id')\" "
				. "onmouseout=\"return nd(1000);\" style='position: relative;'><img vertical-align='middle' class='info' border='0' src='$jsinfoImage'></span>";
				*/
	if($shared_user->isOnProbation()){
		$additional_details['probation_notes'] = str_replace(array("&#039", "'"), '\&#039', $additional_details['probation_notes']);
		$extra = "onmouseover=\"return overlib('" .
		str_replace(array("\rn", "\r", "\n"), array('','','<br />'), $additional_details['probation_notes'])
		. "', CAPTION, '{$app_strings['LBL_PROBATION_NOTE']}"
		. "', DELAY, 200, STICKY, MOUSEOFF, 1000, WIDTH, 310, CLOSETEXT, '<img border=0  style=\'margin-left:2px; margin-right: 2px;\' src=".SugarThemeRegistry::current()->getImageURL('close.gif').">', "
		. "CLOSETITLE, '{$app_strings['LBL_ADDITIONAL_DETAILS_CLOSE_TITLE']}', CLOSECLICK, FGCLASS, 'olFgClass', "
		. "CGCLASS, 'olCgClass', BGCLASS, 'olBgClass', TEXTFONTCLASS, 'olFontClass', CAPTIONFONTCLASS, 'olCapFontClass', CLOSEFONTCLASS, 'olCloseFontClass');\" "
		. "onmouseout=\"return nd(1000);\" ";
		echo '<span '.$extra.'><img vertical-align="middle" class="info" border="0" src="'.$probation_icon.'"></span>';
	}
	echo '</h5>';
}

function set_chooser_js(){
$the_script  = <<<EOQ

<script type="text/javascript" language="Javascript">
<!--  to hide script contents from old browsers

function set_chooser()
{



var shared_ids_def = '';

var display_td = document.getElementById('shared_ids_td');

var display_ref = display_td.getElementsByTagName('select')[0];

for(i=0; i < display_ref.options.length ;i++)
{
//         shared_ids_def += "shared_ids[]="+display_ref.options[i].value+"&";
	display_ref.options[i].selected = "1";
}

//document.shared_cal.shared_ids_def.value = shared_ids_def;

}
// end hiding contents from old browsers  -->
</script>
EOQ;

return $the_script;

}

function editor_historic_rates(){
	global $shared_user, $app_strings, $app_list_strings, $db, $current_language;
	$current_module_strings = return_module_language($current_language, 'edanz_Schedule');

	$query = "SELECT type,
		 MAX(ThisMonthWorkload) AS ThisMonthWorkload,
		 MAX(AverageMonthlyLoad) AS AverageMonthlyLoad,
		 SUM(TotalTasks) AS TotalTasks
	FROM
	(
		SELECT type,
                        SUM(IF(EXTRACT(YEAR_MONTH FROM CURDATE()) = EXTRACT(YEAR_MONTH FROM IFNULL(completed_date, date_due)), workload, 0)) AS ThisMonthWorkload,
                        SUM(workload)/ PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM CURDATE()), EXTRACT(YEAR_MONTH FROM MIN(IFNULL(completed_date, date_due)))) AS AverageMonthlyLoad,
                        COUNT(*) as TotalTasks
                FROM tasks
                WHERE workload IS NOT NULL
                        AND status <> 'Deferred'
                        AND status <> 'Pending Input'
                        AND assigned_user_id = '".$shared_user->id."'
                        AND deleted = 0
                GROUP BY type

		UNION
				
		SELECT task_type AS type,
                        0 AS ThisMonthWorkload,
                        NULL AS AverageMonthlyLoad,
                        IFNULL(historic_task_totals.task_count, 0) as TotalTasks
                FROM historic_task_totals
                WHERE user_id = '".$shared_user->id."'
                GROUP BY type
	) AS rates
	GROUP BY type";

	$result = $db->query($query);
	
        echo "<table ><tr><th></th><th>";
        echo $current_module_strings['LBL_THIS_MONTH_LOAD'];
        echo "</th><th>";
        echo $current_module_strings['LBL_MEAN_MONTH_LOAD'];
        echo "</th><th>";
        echo $current_module_strings['LBL_TOTAL_TASKS'];
        echo "</th></tr>";
	
	while ($row = $db->fetchByAssoc($result)) {
		echo "<tr><td>";
		echo $app_list_strings['task_type_dom'][$row['type']];
		echo "</td><td>";
		echo $row['ThisMonthWorkload'].' '.$app_list_strings['task_type_units'][$row['type']];
		echo "</td><td>";
		echo (empty($row['AverageMonthlyLoad'])?'N/A':round($row['AverageMonthlyLoad']).' '.$app_list_strings['task_type_units'][$row['type']]);
		echo "</td><td>";
		echo $row['TotalTasks'];
		echo "</td></tr>";
	}
	echo "</table>";

	echo "<table style=\"width:100%;\"><tr><td style=\"background-color:#AAD1D7;\">";
	echo $current_module_strings['LBL_PUNCTUALITY'];
	echo "</td><td style=\"background-color:#AAD1D7;\">";
	echo $shared_user->completion_punctuality;
        echo "</td></tr></table>";
/*
        echo "<table style=\"width:100%;\"><tr><td style=\"background-color:#AAD1D7;\">";
        echo $current_module_strings['LBL_PUNCTUALITY'];
        echo "</td><td style=\"background-color:#AAD1D7;\">";
        echo $shared_user->completion_punctuality;
        echo "</td></tr><tr><td style=\"background-color:#AAD1D7;\">";
        echo $current_module_strings['LBL_AVERAGE_QUALITY_RATING'];
        echo "</td><td style=\"background-color:#AAD1D7;\">";
        echo $shared_user->average_quality_rating > 0 ? $shared_user->average_quality_rating : 'N/A';

        echo "</td></tr></table>";
*/

}

// Get aerage quality rating data
function get_average_quality_rating(){
	global $shared_user, $app_strings, $app_list_strings, $db, $current_language;
        $current_module_strings = return_module_language($current_language, 'edanz_Schedule');

	echo '<div style="display:inline-block;border:0px solid #336699;margin-top:3px;"><table><tr><td style="background:none;font-style:italic;font-weight:bolder;">Quality:</td><td title="All time.">';
	echo $shared_user->average_quality_rating >= 0 && isset($shared_user->average_quality_rating) ? $shared_user->average_quality_rating : 'N/A';
	echo '</td>
                        <td title="Last 10 Jobs.">';
        echo $shared_user->ten_quality_rating >= 0 && isset($shared_user->ten_quality_rating)? $shared_user->ten_quality_rating : 'N/A';
        echo '</td>';
        echo '          <td title="Last 3 Jobs.">';
        echo $shared_user->three_quality_rating >= 0 && isset($shared_user->three_quality_rating)? $shared_user->three_quality_rating : 'N/A';
echo '</td>';
echo'                    </tr></table></div>';
}

function get_desired_workload(){
	global $shared_user,$db;
	echo '<div style="display:inline-block;border:0px solid #336699;margin-top:3px;"><table><tr><td style="background:none;font-style:italic;font-weight:bolder;">FTE:</td><td title="Full Time Estimated">';
	$query = "select ifnull(desiredworkload_c,0) as desired_workload from users_cstm uc where uc.id_c = '$shared_user->id'";
	$result = $db->query($query,true," Error getting desired workload : ");
	$row = $db->fetchByAssoc($result);
	if($row != null){
		echo $row['desired_workload']*100;
		echo '%';
	}else{
		echo 'N/A';
	}
	echo '</td>';
	echo '</tr></table></div>';
}

/**
 * Get available point for editor
 */
function get_available_for_job(){
	global $shared_user,$db;
	$today = date ( 'y-m-d', time () );
	$today = date ( 'Y-m-d', strtotime ( "$today +1 day" ) );
	echo '<div style="display:inline-block;border:0px solid #336699;margin-top:3px;"><table><tr><td style="background:none;font-style:italic;font-weight:bolder;">Available for job:</td><td title="Available for job">';
	$query = "SELECT sum(workload_point) as workload_point, DATE_FORMAT(date_add(date_due, interval +8 hour), '%Y-%m-%d') as date_due FROM tasks t WHERE  t.deleted=0 and t.status <> 'Deferred' and date_add(date_due, interval +8 hour)>='$today' and t.assigned_user_id = '$shared_user->id'  group by DATE_FORMAT(date_add(date_due, interval +8 hour), '%Y%m%d') ORDER BY date_due desc  ";
	$result = $db->query($query,true," Error getting available_for_job : ");
	$sum_point = 0;
	$array_workload_point = array ();
	while ( $a = $db->fetchByAssoc ( $result ) ) {
		$array_workload_point = $array_workload_point + array (
				$a ['date_due'] => $a ['workload_point'] 
		);
	}
	
	$DateDifferent = getDateDifferent ( $_REQUEST['due'], $today );
	$date_loop = $_REQUEST['due'];
	$available_day = 0;
	for($workload = 0; $workload < $DateDifferent + 1; $workload ++) {
		$scheduleNotes = getScheduleNotes ( $shared_user->id, $date_loop );
		if ($scheduleNotes || date ( 'w', strtotime ( $date_loop ) ) == 0 || date ( 'w', strtotime ( $date_loop ) ) == 6) {
			$date_loop = date ( 'Y-m-d', strtotime ( "$date_loop -1 day" ) );
			continue;
		}
		$sum_point = $sum_point + $array_workload_point[$date_loop];
		$date_loop = date ( 'Y-m-d', strtotime ( "$date_loop -1 day" ) );
		$available_day = $available_day +1;
	}
	$available_points = get_desired_workload_value () * $available_day;
	$available_for_job = sprintf("%.2f",$available_points - $sum_point);
	$available_for_job_color = 'green';
	if($available_for_job < $_REQUEST['point']){
		$available_for_job_color = 'red';
	}
	echo "<font color=\"" . $available_for_job_color . "\">".$available_for_job."</font>";
	echo '</td>';
	echo '</tr></table></div>';
	
	echo '<div style="display:inline-block;border:0px solid #336699;margin-top:3px;"><table><tr><td style="background:none;font-style:italic;font-weight:bolder;">Workload % before job:</td><td title="Workload % before job">';
	$desired_load_before_job = sprintf("%.0f",$sum_point / $available_points * 100);
	$desired_load_before_job_color = 'green';
	if($desired_load_before_job > 100){
		$desired_load_before_job_color = 'red';
	}
	echo "<font color=\"" . $desired_load_before_job_color . "\">".$desired_load_before_job."%</font>";
	echo '</td>';
	echo '</tr></table></div>';
	
	echo '<div style="display:inline-block;border:0px solid #336699;margin-top:3px;"><table><tr><td style="background:none;font-style:italic;font-weight:bolder;">Workload % with job:</td><td title="Workload % with job">';
	$desired_load_with_job = sprintf("%.0f",($sum_point + $_REQUEST['point']) / $available_points * 100);
	$desired_load_with_job_color = 'green';
	if($desired_load_with_job > 100){
		$desired_load_with_job_color = 'red';
	}
	
	echo "<font color=\"" . $desired_load_with_job_color . "\">".$desired_load_with_job."%</font>";
	echo '</td>';
	echo '</tr></table></div>';
}

function get_desired_workload_value(){
	global $shared_user,$db;
	$query = "select ifnull(desiredworkload_c,0) as desired_workload from users_cstm uc where uc.id_c = '$shared_user->id'";
	$result = $db->query($query,true," Error getting desired workload : ");
	$row = $db->fetchByAssoc($result);
	if($row != null){
		return $row['desired_workload']*100;
	}else{
		return 0;
	}
}

function get_punctuality($editor_id = NULL){
	global $db;
	$query = "SELECT
                        SUM(IF(TIMEDIFF(`completed_date`, `date_due`) < '00:30:00', 1, 0)) as on_time,
                        COUNT(*) as total
                FROM tasks
                WHERE status= 'Completed'
			AND deleted = 0
			AND date_due IS NOT NULL";
	if(!empty($editor_id)){
		$query .= "  AND assigned_user_id = '".$editor_id."'";
	}

	$result = $db->query($query,true," Error getting average punctuality: ");

	$row = $db->fetchByAssoc($result);

	if($row != null && $row['total'] > 0)
	{
		return round(100*$row['on_time']/$row['total']).'%';
	}
	else
	{
		return 'N/A';
	}
}
function getUserTime(){
	global $shared_user, $app_strings, $app_list_strings, $db, $current_language;
	$current_module_strings = return_module_language($current_language, 'edanz_Schedule');
 	$category = 'global';
	$result = $db->query("SELECT contents FROM user_preferences WHERE assigned_user_id='$shared_user->id' AND category = '" . $category . "' AND deleted = 0", true, 'Failed to load user preferences');
	$row = $db->fetchByAssoc($result);
	$userInfo['userInfo'] = unserialize(base64_decode($row['contents']));
	$timezone = $userInfo['userInfo']['timezone'];
	if(empty($timezone)){
		$localtime = "not set";
	}else{
		if($timezone == 'Asia/Beijing')$timezone = 'Asia/Shanghai';
		$date = new DateTime('now', new DateTimeZone($timezone));
		$localtime = $date->format('h:i a');
	}
	echo '<font style="background:none;font-style:italic;font-weight:bolder;">&nbsp;Time:</font>'.$localtime;
}
?>
